package com.lykj.job.core.executor.impl;

import com.lykj.job.core.executor.LykjJobExecutor;
import com.lykj.job.core.handler.annotation.LykjJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


/**
 * lykj-job executor (for frameless)
 *
 * @author cxl 2020-11-05
 */
public class LykjJobSimpleExecutor extends LykjJobExecutor {
    private static final Logger logger = LoggerFactory.getLogger(LykjJobSimpleExecutor.class);


    private List<Object> lykjJobBeanList = new ArrayList<>();
    public List<Object> getLykjJobBeanList() {
        return lykjJobBeanList;
    }
    public void setLykjJobBeanList(List<Object> lykjJobBeanList) {
        this.lykjJobBeanList = lykjJobBeanList;
    }


    @Override
    public void start() {

        // init JobHandler Repository (for method)
        initJobHandlerMethodRepository(lykjJobBeanList);

        // super start
        try {
            super.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void destroy() {
        super.destroy();
    }


    private void initJobHandlerMethodRepository(List<Object> lykjJobBeanList) {
        if (lykjJobBeanList==null || lykjJobBeanList.size()==0) {
            return;
        }

        // init job handler from method
        for (Object bean: lykjJobBeanList) {
            // method
            Method[] methods = bean.getClass().getDeclaredMethods();
            if (methods.length == 0) {
                continue;
            }
            for (Method executeMethod : methods) {
                LykjJob lykjJob = executeMethod.getAnnotation(LykjJob.class);
                // registry
                registJobHandler(lykjJob, bean, executeMethod);
            }

        }

    }

}
